﻿
//系统客户端初始化
(function ($, ibpm) {
    "use strict";
    var page = {
        init: function () {
            // 加载标签写入
            ibpm.loadbarInit();
            setTimeout(function () {
                ibpm.loading(false);
            }, 200);

            /*判断当前浏览器是否是IE浏览器*/
            if ($('body').hasClass('IE') || $('body').hasClass('InternetExplorer')) {
                $('#M_loadbg').append('<img data-img="imgdl" src="' + top.$.rootUrl + '/Content/ie-loader.gif" style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;vertical-align: middle;">');
            }
            else {
                $('#M_form_bg').fadeOut();
            }
            // 通知栏插件初始化设置
            toastr.options = {
                "closeButton": true,
                "debug": false,
                "newestOnTop": true,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "3000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };
        }
    };
    $(function () {
        page.init();
    });
})(window.jQuery, top.ibpm);

//判断是否是js的空对象{} => {}返回true
function isEmptyObject(obj) {
    for (var key in obj) {
        return false;//返回false，不为空对象
    }
    return true;//返回true，为空对象
}

//取URL查询参数部分的关键字对应值
//定义了全局方法
function request(d) {
    //location.search输出？email=someone&id=123    
    for (var c = location.search.slice(1).split("&"), a = 0; a < c.length; a++) {
        var b = c[a].split("=");
        if (b[0] == d)
            if ("undefined" == unescape(b[1]))  //unescape是javascript方法（解码）
                break;
            else
                return unescape(b[1]);
    }
    return "";
};

//删除数组中的元素
function delValInArr(value, array) {
    var pos = $.inArray(value, array);
    array.splice(pos, 1);
}

//对多位小数进行四舍五入
//num是要处理的数字  v为要保留的小数位数
function decimal(num, v) {
    var vv = Math.pow(10, v);
    return Math.round(num * vv) / vv;
}

//验证输入数字，用法：input type="number" οnkeyup="clearNoNum(this)"
function clearNoNum(obj) {
    //修复第一个字符是小数点 的情况.
    if (obj.value != '' && obj.value.substr(0, 1) == '.') {
        obj.value = "";
    }
    obj.value = obj.value.replace(/^0*(0\.|[1-9])/, '$1');//解决 粘贴不生效
    obj.value = obj.value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (obj.value.substr(0, 1) == '0' && obj.value.length == 2) {
            obj.value = obj.value.substr(1, obj.value.length);
        }
    }
}

//--验证金额--
function verifyMoney(obj) {
    var precapital;
    document.querySelector('#' + obj).addEventListener('focus', function () {
        if (this.value == '0.00') {
            this.value = '';
        } else {
            this.value = this.value.replace(/\.00/, '').replace(/(\.\d)0/, '$1');
        }
        precapital = this.value;
    });
    document.querySelector('#' + obj).addEventListener('keyup', function () {
        this.value = this.value.replace(/^[\.]/, '').replace(/[^\d.]/g, '');
        if (this.value.split(".").length - 1 > 1) {
            this.value = precapital;
        }
        precapital = this.value;
    });
    document.querySelector('#' + obj).addEventListener('blur', function () {
        this.value = this.value.replace(/[\.]$/, '');
        this.value = this.value.replace(/(.*)\.([\d]{2})(\d*)/g, '$1.$2');
        this.value = Number(this.value).toFixed(2);
        var logNum = this.value.toString();
        if (logNum.match(/\./g) != null) {
            integerNum = parseInt(logNum).toString().replace(/\d(?=(\d{3})+$)/g, '$&,');
            decimalNum = '.' + logNum.replace(/(.*)\.(.*)/g, '$2');
        }
    });
}

//表单提交（含Token）
function showRequest(formData, jqForm, options) {
    var queryString = $.param(formData);
    //alert(queryString);
    var param = {};
    param['DataText'] = new Base64().encode(queryString);
    top.ibpm.loading(true, '正在提交数据');
    setTimeout(function () {
        top.ibpm.httpAsyncPost(top.$.rootUrl + jqForm.attr('action'), param, function (result) {
            if (result.code === 200) {
                if (result.url != undefined && result.url != '' && result.url != null)
                    window.location.href = result.url;
                else {
                    jqForm.resetForm();
                    if (result.info != undefined && result.info != '' && result.info != null)
                        top.ibpm.alert.success(result.info);
                    if (typeof EndReq === "function") {
                        if (result.data != undefined && result.data != '' && result.data != null)
                            EndReq(result.data);
                        else
                            EndReq();
                    }
                }
            } else {
                top.ibpm.alert.error(result.info);
            }
        });
    }, 50);
    return false;
};

//提交拦截
function FormSaveReport(id) {
    var options = {
        beforeSubmit: showRequest,
        resetForm: true,
        timeout: 3000
    };
    var exp = $('#ValExp');
    if (!!exp) {
        var vexp = exp.val();
        if (!!vexp) {
            var re = new RegExp("=", "g");
            vexp = vexp.replace(re, "◇");
            exp.val(vexp);
        }
    }
    $("#" + id).ajaxSubmit(options);
    return false;
};

//格式化
function Base64() {
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    }
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};
/** 数字金额大写转换(可以处理整数,小数,负数) */
function smalltoBIG(n) {
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}
//打印代码
function page1Print() {
    var printStr = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body >";
    var content = "";
    var str = document.getElementById('page1').innerHTML;
    content = content + str;
    printStr = printStr + content + "</body></html>";
    var pwin = window.open("Print.htm", "print"); //如果是本地测试，需要先新建Print.htm，如果是在域中使用，则不需要
    pwin.document.write(printStr);
    pwin.document.close(); //这句很重要，没有就无法实现
    pwin.print();
}
function printTable(ro) {
    var row = 16;  //默认分页16行,demo中参数是3行
    if (ro != undefined) {
        row = ro;
    }
    var $tbl = $('table.printTable');
    var $tableparent = $tbl.parent();
    var $thead = $tbl.find('thead');
    //  var $tfoot = $tbl.find('tfoot');
    var $tbody = $tbl.find('tbody');
    var $tbodyTr = $tbody.children();
    var $clonefirstTr = $tbodyTr.first().clone();
    $clonefirstTr.children().each(function () {
        $(this).html('&nbsp;');
    })
    //打空白行
    var tbodyTrlength = $tbodyTr.length;
    var addrow = 0;
    var remainder = tbodyTrlength % row;
    var nulltr = "";
    if (remainder != 0) {
        addrow = row - remainder;
        for (var i = 0; i < addrow; i++) {
            nulltr += $clonefirstTr[0].outerHTML;
        }
    }
    $tbody.append(nulltr); //空白行加入到文档
    //再一次获取所有的tr行
    $tbodyTr = $tbody.children();
    //清空tbody
    $tbody.children().remove();
    //再获取整个表格(此时的表格tbody已经没东西了,这样解释是不是有点啰嗦了?)
    $tbl = $('table.printTable');
    //创建一个文档碎片(这里没有用文档碎片了,jQuery操作字符串更简单)
    var fragment = '';
    //给表格加16行tr(主体内容)
    tbodyTrlength = $tbodyTr.length;
    var trFG = '';
    for (var i = 0; i < tbodyTrlength; i++) {
        trFG += $tbodyTr.eq(i)[0].outerHTML;
        if ((i + 1) % row == 0) {
            var clonetbl = $tbl.clone();  //克隆一个表格
            clonetbl.find("tbody").append(trFG);//在表格的body中加入内容
            fragment += clonetbl[0].outerHTML + "<div style='page-break-after:always;'><br/></div>";    //把表格加入文档碎片中
            trFG = '';
        }
    }
    $tbl.before(fragment);
    $tbl.remove();
}
